//获取应用实例-在appjs中

var WxParse = require('../../utils/wxParse/wxParse.js');
var http = require('../../service/http.js');//请求类
var util = require('../../utils/util.js');//工具类

const app = getApp();
var t = '';//用于清除计时事件
var progress = '';//用于清除加载进度条
//用于保存BMap.search接口返回的数据
var wxMarkerData = [];  
Page({
  /**
   * 页面的初始数据
   */
  data:{ 
    showLoadding: true,//加载动画gif
    //回到顶部--------------------------------
    scroll_top: 0,//初始化滚动条距离顶部位置
    showTopBtn:false,//是否显示回到顶部
    scrollViewHeight: 0,//滚动窗口高度

    windowWidth: '',//窗口宽度
    windowHeight: '',//窗口高度

    canvasViewHeight:'',//海报高度
    canvasViewWidth: '',//海报宽度
    //-----登录------------------------------
    isshow: false,//是否显示mask
    isLogin: false,//是否点击了登录按钮
    isAuthorization: false,//是否授权登陆

    toBuy: false,//是否是立即购买
    isActive: 0,//是否被选
    itemPrice:'',//item价格
    itemImg:'',//sku小图
    cartObject:{},
    showLogin: false,//是否展示登录
    showSkuList:false,//点击加入购物车展示购物车商品sku
    showPage:'',//页面加载后进行展示
    progressAnimation:'',//加载动画
    progressHeight: 3,//进度条高度
    progressPercent:0,//进度条百分比
    progressOp:1,//进度条透明度
    // showProgress:true,//展示进度条

    //---------------跳转url------------------------
    pageUrl:'',

    //---------------利润显示------------------------
    minFxFee:0,//最小利润
    maxFxFee: 0,//最大利润
    minFxFeeRate: 0,//最小利润率
    maxFxFeeRate: 0,//最大利润率
    isViewFxFeeDetail:0,//  小程序商品详情是否显示分销费用(1: 是 / 0: 否)
    
    //----------------百度地图数据------------------------------------------

    mapHeight: 'auto',//地图高度
    markers: [],//标注点
    latitude: '',//经度
    longitude: '',//纬度
    placeData: {} ,

     //---商品相关---------------------------------------------------
    products:[],//所有商品
    product:{},//商品
    minPrice: 0,//最小价格（初始化商品价格范围）
    maxPrice: 0,//最大价格

    skuTitles: [],//sku中title
    skus: [],//所有sku内容
    distAttrs: [],
    chooseAttrids: [],//已选属性id
    isLimited:false,//是否为限购商品
    limitedNum:0,//限购数量
    proImgs: [], //商品主图轮播

    //----------暂存购物车商品信息-------------------
    itemId: '',//暂存购物车商品id 
    skuId: '',//skuid
    count: 1,//购物车数量
    stock: 0,  //默认库存
    pIndex:'',//商品下标
    toShow:'',//购物车弹窗类型；
    itemPrice : 0, //商品显示价格
    showSmImg: false,//展示购物车小图
    //--------分享商品动画------------------------------
    
    shareImgUrl:'',//分享图片地址
    showCanvas:false,//用于生成图片
    codeUrl:'',//分享码地址
    // shareCanvasWidth:'',//预览窗口宽度
    left:'',//预览窗口偏移量
    isshowcanvasMask:false,//分享图片蒙层
    canvasHeight: 0,//设置canvas高度----
    canvasWidth: 0,//设置canvas宽度----
    posterUrl:'',//海报资源路径
    shareProduct:false,//是否展示分享菜单
    showSettingBox:false,//打开引导用户设置弹出层
    authorizeMsg:'',//授权信息提示
    localPosterUrl: '',//本地海报路径

    //----------商品分享分享人inviter-店铺id------------------------------
    shopInfo: {},//店铺信息，用于控制展示分销利润
    inviter: '',//分享人inviter(通过二维码扫描进入小程序获取)
    shopuid:'',//店铺id
    inShareShop:false,//是否有分享店铺
    isShareLink:false,//是否为分享的链接
    shareKey: '',//shareKey =='0'为分享标识

    //---------电话绑定情况--------------------
     isBindPhone : false,
     //------用户绑定手机操作-------------
    animationData: '',//遮罩层动画
    scorllTopAnimationData:'',//回到顶部动画
    isPhone: false,//验证手机号是否成功
    getCode: app.data.getCode,//是否已经获取验证码
    codeTime: app.data.codeTime,//验证码有效时间
    phoneNum: '',//输入绑定的手机号
    sendCode: false,//已经触发发送验证码
    showBindPhoneModel: false,//绑定手机模态框
    //-----------购物车商品数量----------------------
    cartCount: 0,
    // ----------分享图片点击预览--------------------
    previewUrl: '',//生成分享图片临时地址
    //商品详情转化-------------------------
    itemDesc:'',//商品详情
    // ----------视频播放----------------------------
    showVideo:false,//是否播放视频
  },
  /**
   * 生命周期函数--监听页面加载，用于接收参数
   */
  onLoad: function (parameter) {//parameter--productId为商品id
    console.log('商品页所有参数');
    console.log(parameter);

    var that = this;
    //获取进度条进度
    that.getProgress();
   
    //本地店铺信息
    let shopInfo = wx.getStorageSync('shopInfo') || {} ;
    //商品id 和 分享人uid、店铺id,是否在分销店铺，转发标识
    let [productId, inviter, shopuid, shareKey] = ['', '', '',''];

    //------列表页请求单个商品详细信息 ---------------------------------
    if (parameter.productId) {
      console.log('列表页请求单个商品详细信息');
      productId = parameter.productId;//商品id
      shopuid = parameter.shopuid || '';//店铺id
    } else if (parameter.parms){//通过转发分享进商品详情页
      console.log('通过转发分享进商品详情页');
      let parms = parameter.parms.split('/');
      productId = parms[0];//商品id
      inviter = parms[1];//分享人
      shopuid = parms[2];//店铺id
      shareKey = parms[3];//转发标识
    }
    //-----------通过扫描二维码 进入商品页 -----------------------------
    else if (parameter.q) { 
      let scan_url = decodeURIComponent(parameter.q);
      console.log( scan_url);
      let parm = scan_url.split('?')[1];//当前所有参数
      let ids = parm.split('/');
      productId = ids[0];//商品id
      inviter = ids[1];//分享人uid
      shopuid = ids[2];//店铺id
      shareKey = ids[3];//转发标识
    } 
    //------------通过小程序码进入商品详情-------------------------------
    else if (parameter.scene) {  
      console.log(parameter.scene);
      let scene = decodeURIComponent(parameter.scene);
      let param = scene.split('/');
      productId = param[0];//商品id
      inviter = param[1];//分享人uid
      shopuid = param[2];//店铺id
      shareKey = param[3];//转发标识
    } 
    //------------没有接收到参数-----------------------------------------
    else {
      console.log("请求缺少参数productId");
    }
    //空字符串拦截
    shopuid = (shopuid == "''" ? '' : shopuid);

    //设置参数
    that.setData({
      itemId: productId,
      inviter: inviter,
      shopuid: shopuid,
      shareKey: shareKey,//shareKey =='0'为分享标识
      scrollViewHeight: app.data.windowHeight,//滚动窗口高度
      windowWidth: app.data.windowWidth,//窗口宽度
      windowHeight: app.data.windowHeight,//窗口高度
    }) 
    console.log("商品id:" + productId + "分享人inviter:" + inviter + "店铺idshopuid:" + shopuid + 'shareKey:' + shareKey);

    //如果用户已经登录 等待checkSession结果 查看本地店铺信息----已经登录并且有自己的店铺，直接查找商品详情
    var getAuthorizationTask = setInterval(function(){
      let isAuthorization = app.data.isAuthorization;
      if (isAuthorization === true || isAuthorization === false){
        if (isAuthorization){
          clearInterval(getAuthorizationTask);
          if (shopInfo.isOwnShop !== '1' && shareKey == '0') {//用户已登录 没店铺
            //根据inviter 和shopInfo 根据参数查询店铺信息、订单数量、商品信息
            that.setShopInfo();
          } else {//自己的店铺
            //根据店铺id 查商品
            that.QueryitemByItemId();
            //获取订单、购物车数量
            that.getElementsCounts();
          }
          //设置授权信息
          that.setData({
            isAuthorization: app.data.isAuthorization,
            isBindPhone: wx.getStorageSync('isBindPhone'), //根据绑定状态获取用户授权
          })

        }else{
          let showLogin = that.data.showLogin
          if (showLogin !== true) {//未展示登录
            that.loginAnimation();
            return;
          }
        }
      }
    },100)
   
  },
  onReady: function () {
    
  },
  onShow:function(){//
    let that = this;
    app.checkSession(that);//携带分享店铺信息
  },
  getElementsCounts:function(){
    app.getElementsCounts();
    this.setData({
      cartCount: app.data.cartCount,//购物车数量；
    })
  },
  //---------------------------点击选择商品属性---------------------------------
  selectValue:function(e){
    app.selectValue(e);
    this.setData({
      distAttrs: app.data.distAttrs,
      chooseAttrids: app.data.chooseAttrids,
      itemId: app.data.itemId,
      skuId: app.data.skuId,
      stock: app.data.stock,
      count: app.data.count,
      itemPrice: app.data.itemPrice,
      itemImg: app.data.itemImg
    })
    console.log("selectValue:app.data.skuid---" + app.data.skuId);
    console.log(this.data.itemPrice);
  },

  changeCount: function (e) {//改变数量
    app.changeCount(e, this);
    this.setData({
      count: app.data.count,
      stock: app.data.stock
    })
  },
  minsCount: function (e) {//减少数量
    app.minsCount(e, this);
    this.setData({
      count: app.data.count,
      stock: app.data.stock
    })
  },
  addCount: function (e) {//增加数量
    app.addCount(e, this);
    this.setData({
      count: app.data.count,
      stock: app.data.stock
    })
  },
  getToBuy:function(e){//是否为立即购买
    console.log("productjs--getToBuy");
    app.getToBuy(e);
    this.setData({
      toBuy: app.data.toBuy
    })
  },
  addmessage: function (e) {//选择商品信息
    console.log('查看购物车');
    var that = this;
    //---------------判断手机号是否绑定---------------
    let isBindPhone = wx.getStorageSync('isBindPhone');
    let product = that.data.product;
    let isLimited = product.isLimited;   //判断该商品是否为限购商品
    let toShow = that.data.toShow;//购物车弹出 类型

    //改变购物车按钮样式
    if(e){
      toShow = e.currentTarget.dataset.type;
      console.log('查看购物车--getToBuy');
      that.getToBuy(e);
    }
    that.setData({
      toShow: toShow
    })
    //如果是限购且未绑定手机
    if (isLimited == '1' && !isBindPhone) {
      console.log('弹出绑定手机弹窗');
      //弹出绑定手机弹窗
      that.showBindTip();
      that.bindPhone();
      that.getToBuy(e);//用户是否点击了立即购买
      return;
    }
    //调用全局方法
    wx.showLoading({
      title: '加载中',
      mask: true,
      success: function(res) {
        app.addmessage(that);
        app.getStock(that);//获取库存
        app.getSkuValue(product);//获取sku所有属性
        that.makeAnimation(toShow);//弹出购物车动画
        //更新商品sku

        console.log("addmessage:app.data.skuid---" + app.data.skuId);
        that.setData({
          toBuy: app.data.toBuy,//控制购买/下一步按钮状态
          skus: app.data.skus,
          skuTitles: app.data.skuTitles,
          distAttrs: app.data.distAttrs,
          cartProducts: app.data.cartProducts,
          chooseAttrids: app.data.chooseAttrids,
          itemId: app.data.itemId,
          skuId: app.data.skuId,
          count: app.data.count,
          stock: product.stock,
        })
        wx.hideLoading();
      }
    })
    //更新商品以及商品库存
    setTimeout(function () {
      that.setData({
        product: app.globalData.product,
        stock: app.data.cartStock,
      })
    }, 1000)
  },
  //------------------关闭/开启购物车动画----------------
  cancelAnimation: function (toCancel){
    let that = this;
    app.cancelAnimation();
    //showSkuList、shareProduct分别为判断显示弹出内容
    this.setData({
      showSkuList: false,
      shareProduct: false,
      animationData: app.data.animationData,//加入购物车动画
    })
    //动画延时播放
    setTimeout(function () {
      that.setData({
        isshow: app.data.isshow,
        showLogin: app.data.showLogin,
        showSmImg: false,//展示购物车小图
        isLogin: false,//是否点击了登录按钮
        animationData: app.data.animationData,//加入购物车动画
      })
    }.bind(this), 300)
  },
  makeAnimation:function(toShow){
    let that = this;
    let [showSkuList, shareProduct] = ['',''];
    app.makeAnimation();

    //showSkuList、shareProduct分别为判断显示弹出内容
    if (toShow == 'add' || toShow == 'submit'){//播放加入购物车动画
      showSkuList = true;
    } else if (toShow == 'shareProduct'){//播放分享菜单动画
      shareProduct = true;
    }
    this.setData({
      isshow: app.data.isshow,
      showSkuList: showSkuList,
      shareProduct: shareProduct,
      animationData: app.data.animationData,//加入购物车动画
    })
    setTimeout(function () {
      that.setData({
        showSmImg:true,
        animationData: app.data.animationData,//加入购物车动画
      })
    }.bind(this), 100)
  },
  unAddMessage: function (e) {//关闭
    let that = this;
    let toCancel = e.currentTarget.dataset.type;//关闭动画类型
    that.cancelAnimation(toCancel);
    app.unAddMessage();
    setTimeout(function () {
      that.setData({
        toBuy: app.data.toBuy,
        showSmImg: false,//展示购物车小图
        skus: app.data.skus,
        distAttrs: app.data.distAttrs,
        chooseAttrids: app.data.chooseAttrids,
        itemId: app.data.itemId,
        skuId: app.data.skuId,
        count: app.data.count,
        stock: app.data.stock,
        itemPrice: app.data.itemPrice,
        itemImg: app.data.itemImg,
        showSkuList: false,
      }) 
      console.log('itemId--' + app.data.itemId);
      console.log('unAddMessage：skuId--' + app.data.skuId);
      console.log('count--' + app.data.count);
      console.log('stock--' + app.data.stock);
    }, 200)
  },

  validateSKU:function(){//对购物车所选sku 进行验证
    return app.validateSKU(this);
  },
  addCart: function (e) {//加入购物车
    let that = this;
    //验证sku 
    let validate = that.validateSKU();
    if (validate){//通过验证关闭动画
      let toCancel = e.currentTarget.dataset.type;//关闭动画类型
      that.cancelAnimation(toCancel);//关闭加入购物车窗口
    }else{
      return;
    }
    let pageUrl = that.data.pageUrl;
    if (e.currentTarget.dataset.pageurl){
      pageUrl = e.currentTarget.dataset.pageurl;
    }
    that.setData({
      pageUrl: pageUrl,
    })
    app.addCart(e, that);
    //加入购物车后初始化count、
    setTimeout(function () {
      console.log('app.data.isAuthorization--' + app.data.isAuthorization);
      let cartCount = app.data.cartCount;//购物车数量
      that.setData({
        toBuy: app.data.toBuy,
        count: app.data.count,
        showLogin: app.data.showLogin,
        animationData: app.data.animationData,
        cartCount: app.data.cartCount
      })
    }, 1500)
  },
  //==================获取地理位置======================================
  getLocation:function(){
    let that = this;
    let placeData = that.data.placeData;
    if (placeData){
      //打开剧场位置
      wx.openLocation({
        latitude: parseFloat(placeData.pointX) ,
        longitude: parseFloat(placeData.pointY),
        //scale: '',//缩放比例
        name: placeData.name,
        address: placeData.address,
        success: function(res) {
            console.log("打开剧场位置成功");
        }
      })
    }
 
  },
  //============回到主页================================================
  backToHome: function (e) {//返回到首页
    app.backToHome(this);
  },
  toCartPage:function(){//跳转到我的购物车
    let pageUrl = '/pages/shopingCart/shopingCart';
    let that = this;
    //that.data.pageUrl = pageUrl;//需要要跳转的页面
    that.setData({
      pageUrl: pageUrl,
      toCartPage:true,
    })
    wx.switchTab({
      url: pageUrl
    })
  },
  
  //-------登陆动画-------------------
  loginAnimation: function () {
    wx.hideTabBar();//隐藏底部菜单
    app.loginAnimation();
    console.log('app.data.showLogin' + app.data.showLogin);
    this.setData({
      isAuthorization: app.data.isAuthorization,
      animationData: app.data.animationData,
      showLogin: app.data.showLogin,
    })
  },


  onShareAppMessage: function (options){//微信分享
    console.log('转发途径:')
    console.log(options)
    // 分享来源，分享人id(谁转发 谁是分享人)
    let [that, shareFrom, inviter, product, shopInfo] = [this, options.from, wx.getStorageSync('unionid') || '', this.data.product, wx.getStorageSync('shopInfo')];
    console.log('分享店铺信息');
    console.log(wx.getStorageSync('shopInfo'));
      let isAuthorization = app.data.isAuthorization;
      if (isAuthorization !== true) {//未登录播放登录动画
        that.loginAnimation();
        util.showToast('您还未登录，请在登陆后分享~', 2000, 'none', function () { });
        return;
      } else {
         // 转发所需参数商品id 和 分享人uid和 店铺id
        //分享标题、商品id、店铺id、分享图标
        let [shareTitle, productId, shopuid, shareImg] = [product.itemName, product.id, shopInfo.shopuid || '', product.itemimags[0].imgs];
        console.log("商品id" + productId +"分享人id" + inviter + "店铺shopuid"+ shopuid);
        //通过分享菜单的按钮分享
        if (shareFrom !== 'menu') {
          that.cancelShare(options);//收起菜单
        }
        return {
          title: shareTitle,
          imageUrl: shareImg,
          path: '/pages/product/product?parms=' + productId + '/' + inviter + '/' + shopuid +'/0'
        }
      }

  },
  shareProduct: function (e) {//商品分享
    console.log("商品分享" + e);
    this.setData({
      showVideo:false
    })
    let toShow = e.currentTarget.dataset.type;
    this.makeAnimation(toShow);
  },
  cancelShare:function(e){//关闭分享菜单
    let toCancel='';
    if(e){
      toCancel = e.target.dataset.type;//关闭动画
    }
    this.cancelAnimation(toCancel);
  },

  makeCode: function (e) {//生成分享图片
    console.log("生成分享图片");
    console.log(e);
    //分享参数------------------------------------------
    let shopInfo = wx.getStorageSync('shopInfo');
    let [that, shopuid, rdSession, requestUrl, code] = [this, shopInfo.shopuid || '' , wx.getStorageSync('rd_session'), '', e.currentTarget.dataset.code];//店铺id、Session、请求路径、
    //设置蒙层
    that.setData({
      isshowcanvasMask:true,
    })
    let product = that.data.product;
   // let content ="https://wx.mamatx.com.cn/weixin/product?itemId=" + product.id
   //用于生成商品二维码路径
    let content = "https://wx.mamatx.com.cn/weixin/product?" + product.id 
    console.log(content);
    if (code == "littleCode"){//生成小程序码
      requestUrl = '/weixin/getQRCode/mini'
    } else if (code == "popPoster"){//生成推广海报
      requestUrl = '/weixin/getQRCode/zjYouXuan'//'/weixin/getQRCode/zjYouXuan'
    }else{//生成商品二维码
      requestUrl = app.data.baseUrl + "/weixin/getQRCode/normal"
    }
    console.log('生成小程序码店铺shopuid:' + shopuid);
    //------------------------------获取分享码请求--------------------------------------
    wx.showLoading({
      title: '生成中',
      mask:true,
      success:function(res){
        http.getReq(requestUrl, {
          content: content,
          rdSession: rdSession,
          sceneStr: product.id,//商品id
          shopuid: shopuid,//店铺id
          page: "pages/product/product",//小程序跳转路径
        }, function (res_re) {
          console.log('返回二维码/小程序码路径')
          console.log(res_re);
          that.setData({
            showCanvas: true,
          })

          //下载文件资源到本地 存为临时路径
          wx.downloadFile({
            url: res_re,//商品图片地址
            success: function (sres) {
              console.log(sres);
              console.log("小程序/二维码码路径" + sres.tempFilePath);
              that.data.codeUrl = sres.tempFilePath; //下载后的文件的临时路径
              that.previewImg();
            }
          })

        });
      }
    })
  },

  previewImg: function () {//预览分享图片
    let that = this;
    setTimeout(function () {
      //展示分享图片 和 和蒙层
      wx.createSelectorQuery().select('#myCanvas').boundingClientRect(function (rect) {
        console.log("节点的高度" + rect.height);
        //-------------绘制分享图片----------------------------------
        let [product, sysInfo, canvasWidth, canvasHeight] = [that.data.product, wx.getSystemInfoSync(), rect.width, rect.height];//预览窗口宽度、获取到商品信息、获取到商品信息、画布宽度、画布高度
        that.setData({
          canvasHeight: canvasHeight,
          canvasWidth: canvasWidth
        })
        console.log("设置canvas高度--" + canvasHeight);
        console.log("设置canvas宽度--" + canvasWidth);
        //绘制图片--获取绘图canvas下文
        let context = wx.createCanvasContext('myCanvas', this);
        let [posterUrl, shareTitle, codeUrl] = [that.data.posterUrl, product.itemName, that.data.codeUrl] ;//海报路径，分享标题，二维码、小程序码

        if (product.posterUrl) {
          context.drawImage(posterUrl, 0, 0, canvasWidth, canvasHeight);
        } else {
          context.setFillStyle("#fff");
          context.fillRect(0, 0, canvasWidth, canvasHeight)//底子 rpx 简化为px 
          console.log("posterUrl:" + posterUrl);
          
          //价格 price、获取商品sku
          let [sharePrice, skus, minPrice] = ['', product.skus, that.data.minPrice];
          if (skus.length > 0) {
            sharePrice = minPrice
          } else {
            sharePrice = product.price;
          }
          
          if (canvasWidth <= 250){//手机查看海报
            context.drawImage(posterUrl, canvasWidth * 0.05, canvasWidth * 0.05, canvasWidth * 0.9, canvasHeight * 0.7);
            console.log(shareTitle);
            //填充商品标题  文字大小
            context.setFontSize(12)
            if (shareTitle.length <= 13) {
              context.setFillStyle('black');
              context.fillText(shareTitle, canvasWidth * 0.05, canvasHeight * 0.7 + 40);
            } else {//文字换行
              context.setFillStyle('black');
              context.fillText(shareTitle.substring(0, 13), canvasWidth * 0.05, canvasHeight * 0.7 + 40);
              if (shareTitle.length >= 26) {
                context.fillText(shareTitle.substring(13, 25) + '...', canvasWidth * 0.05, canvasHeight * 0.7 + 60);
              } else {
                context.fillText(shareTitle.substring(10, shareTitle.length), canvasWidth * 0.05, canvasHeight * 0.7 + 60);
              }
            }
            context.setFontSize(18)//填充文字大小
            context.setFillStyle('red');
            context.fillText("￥" + sharePrice, canvasWidth * 0.05, canvasHeight * 0.7 + 90);
            console.log("canvasWidth:" + canvasWidth);
          }else{
            //绘制商品图片
            context.drawImage(posterUrl, canvasWidth * 0.05, canvasWidth * 0.05, canvasWidth * 0.9, canvasHeight * 0.7);
            //填充商品标题  文字大小
            context.setFontSize(22)
            if (shareTitle.length <= 13) {
              context.setFillStyle('black');
              context.fillText(shareTitle, canvasWidth * 0.05, canvasHeight * 0.7 + 70);
            } else {//文字换行
              context.setFillStyle('black');
              context.fillText(shareTitle.substring(0, 13), canvasWidth * 0.05, canvasHeight * 0.7 + 70);
              if (shareTitle.length >= 26) {
                context.fillText(shareTitle.substring(13, 25) + '...', canvasWidth * 0.05, canvasHeight * 0.7 + 100);
              } else {
                context.fillText(shareTitle.substring(10, shareTitle.length), canvasWidth * 0.05, canvasHeight * 0.7 + 100);

              }
            }
            context.setFontSize(36)//填充文字大小
            context.setFillStyle('red');
            context.fillText("￥" + sharePrice, canvasWidth * 0.05, canvasHeight * 0.7 + 154);
            console.log("canvasWidth:" + canvasWidth);
          }
          
        }
       
        //画小程序码/二维码--------------------------
        console.log("codeUrl:" + codeUrl);
        console.log('canvasWidth:' + canvasWidth);

        let [miniCodeWidth, paddingWidth] = [60,74];//二维码宽高，距离底边距离；

        if (canvasWidth > 250){//ipad上显示
          miniCodeWidth = 110;
          paddingWidth = 132;
        }
     
        context.drawImage(codeUrl, canvasWidth - paddingWidth, canvasHeight - paddingWidth, miniCodeWidth, miniCodeWidth);
        //绘制
        context.draw();
        wx.hideLoading();
      }).exec();
    }, 500);
  },

  saveShareImg:function(e){//保存生成图片
    let that = this;
    let canvasWidth = that.data.canvasWidth;//画布宽度
    let canvasHeight = that.data.canvasHeight;//画布高度
 
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      canvasId: 'myCanvas',
      fileType: 'png',
      success: function (res) {
        console.log(res)
        //reImgUrl: res.tempFilePath
        console.log("生成分享图片地址" + res.tempFilePath);
        //获取用户授权情况
        wx.authorize({
          scope: 'scope.writePhotosAlbum',
          success(rr) {
            console.log(rr);
            console.log('授权成功');
            //生成图片保存本地
            wx.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: function (save_res) {
                console.log(save_res);
                util.showToast('保存成功', 1000, 'none', function () { });
                
                that.cancelShare(e);
                //收起菜单 隐藏绘画
                that.cancelShareImg();
              }
            })
          },
          fail(rr){
            console.log(rr);
            console.log('未授权保存图片失败');
            //收起菜单 隐藏绘画
            that.cancelShareImg();
            that.cancelShare(e);

            //展示提示窗
            that.setData({
              localPosterUrl: res.tempFilePath,//本地海报路径
            })
            that.showSettingBox();
            
            
            //打开设置
            // wx.getSetting({
            //   success(set_res) {
            //     if (!set_res.authSetting['scope.writePhotosAlbum']) {//若用户没有授权打开授权洁面
            //       //打开设置
            //       wx.openSetting({
            //         success: function(open_res) {
            //           console.log('打开设置');
            //           console.log(open_res);
            //           if (open_res.authSetting['scope.writePhotosAlbum']){
            //               wx.saveImageToPhotosAlbum({
            //                 filePath: res.tempFilePath,
            //                 success: function (save_res) {
            //                   console.log(save_res);
            //                   wx.showToast({
            //                     title: '保存成功',
            //                   })
            //                   that.cancelShare(e);
            //                   //收起菜单 隐藏绘画
            //                   that.cancelShareImg();
            //                 },
            //                 fail:function(){

            //                 }
            //               })
            //             }else{
            //               wx.showToast({
            //                 title: '请打开设备重新设置，否则不能保存图片到设备里',
            //                 icon: 'none',
            //                 duration: 1500,
            //                 mask: true
            //               })
            //             }
            //         }, 
            //       })
            //     }
            //   },
            // })
          }
        })
      }
    })
  },
  //关闭分享图片
  cancelShareImg:function(){
    console.log("关闭分享图片");
    this.cancelAnimation();
    this.setData({
      showCanvas:false,
      isshowcanvasMask:false
    })
  },
  //拨打电话
  makePhoneCall:function(e){
    console.log(e);
    let telnum = e.currentTarget.dataset.telnum;
    wx.showModal({
      content: '拨打' + telnum +'?',
      showCancel: true,
      cancelText: '取消',
      confirmText: '确定',
      success: function(res) {
        if(res.confirm){
          wx.makePhoneCall({
            phoneNumber: telnum,
            success: function (res) {
              console.log("拨打电话");
            }
          })
        }
      }
    }) 
  },
  //弹出绑定提示
  showBindTip:function(){
    let that = this;
    util.showToast('该商品需要绑定手机，请您先绑定手机后操作', 1500, 'none', function () {
      setTimeout(function () {
        that.bindPhone();
      }, 1000)
     });
  },


  
  //-------------------绑定手机号相关操作--------------------
  //---------------用户绑定手机号弹出框-------------------------
  bindPhone: function (e) {
    console.log('用户绑定手机号');
    console.log(e);
    this.makeAnimation();
    this.setData({
      // animationData: app.data.animationData,
      // opMask: app.data.opMask,
      showBindPhoneModel: true,
      isshow:app.data.isshow,
    })
  },
  //验证手机号码
  testPhone: function (e) {
    app.testPhone(e);
    this.setData({
      isPhone: app.data.isPhone,
      phoneNum: app.data.phoneNum
    })
  },
  //获取验证码
  getPhoneCode: function (e) {
    let that = this;
    that.setData({
      codeTime: 60,//计时
      sendCode: true,//已经触发发送验证码(控制按钮状态)
    })
    app.getPhoneCode(e, this);
    //如果已经获取到验证码则开始倒计时
    setTimeout(function () {
      let getCode = app.data.getCode;
      console.log('是否已经发送getCode==' + getCode);
      that.setData({
        getCode: getCode,
      })
      if (getCode) {//发送验证码请求成功
        that.countTime();
      } else {//发送验证码请求失败
        that.setData({
          codeTime: 60,
          sendCode: false,
          getCode: false,
        })
      }
    }, 1000)
  },
  //倒计时时间（需要在本方法内执行）
  countTime: function () {
    //let codeTime = this.data.codeTime;
    console.log("倒计时---" + this.data.codeTime);
    let [that, codeTime] = [this, this.data.codeTime]
    codeTime = codeTime - 1;
    if (codeTime == 0) {
      console.log("停止倒计时 getCode:false");
      clearTimeout(t);
      that.setData({
        getCode: false,
        sendCode: false,
        codeTime: 60 //初始化验证码过期时间
      })
      return
    } else {
      that.setData({
        codeTime: codeTime
      })
      t = setTimeout(function () {
        that.countTime();
      }, 1000)
    }

  },
  //-提交表单
  savePhoneNum: function (e) {
    console.log("提交表单savePhoneNum");
    console.log(e);
    let that = this;
    let validate = app.validateSavePhoneForm(e,that);//验证表单是否合法
    if (validate){
      app.savePhoneNum(e, that);
      setTimeout(function () {
        if (app.data.isBindPhone && !app.data.isshow) {
          clearTimeout(t);
          //用户绑定手机后弹出立即购买或者加入购物车
          that.addmessage();
        }
        that.setData({
          isBindPhone: app.data.isBindPhone,
          isshow: app.data.isshow,
          showBindPhoneModel: false,
          codeTime: app.data.codeTime,
          getCode: app.data.getCode
        })
      }, 1000)
    }
  },
  //关闭绑定手机模态框
  closeModel: function () {
    console.log("停止倒计时 getCode:false");
    clearTimeout(t);
    this.setData({
      showBindPhoneModel: false,
      isshow:false,
      getCode: false, //还未获取验证码
      sendCode: false//是否点击发送
    })
  },
  //手机预览图片
  previewImage:function(e){
    app.previewImage(e);
  },
  //------------根据商品id查商品信息---------------------------------------------------------
  QueryitemByItemId: function () {
    console.log('QueryitemByItemId');
    let [that, shopuid, productId] = [this, '', this.data.itemId];//商品id

    //用于显示在商品详情内显示用户的利润信息
    let rdSession = wx.getStorageSync('rd_session');
    //用于根据session查看店铺内是上架分享过来的商品
    let shopInfo = wx.getStorageSync('shopInfo');
    console.log(shopInfo);

    if (shopInfo.shopuid){
      shopuid = shopInfo.shopuid;
    }

    http.getReq('/weixin/item/QueryitemByItemId', {
      productId: productId,
      shopuid: shopuid,
      rdSession: rdSession
    }, function (res) {
      console.log('返回商品信息');
      console.log(res);

      let [product, shareKey] = [res.data, that.data.shareKey];

      if (res.ret) {
        // 图片为空替换默认图片
        if (!product.itemimags[0]) {
          let itemimags = {};
          itemimags.imgs = app.data.defaultImgUrl;
          product.itemimags[0] = itemimags;
        }

        let [placeData, itemDesc, posterUrl, skus, skuPrices, proImgs] = [product.sysTheatre || null, product.itemDescImg || '', product.posterUrl || product.itemimags[0].imgs, product.skus, [], []];//地址信息,商品详情 ,获取海报资源路径、主图轮播

        let [minPrice, maxPrice] = [0, 0];//价格区间
        let [minFxFee, maxFxFee, minFxFeeRate, maxFxFeeRate, isViewFxFeeDetail] = [that.data.minFxFee, that.data.maxFxFee, , that.data.minFxFeeRate, that.data.maxFxFeeRate, that.data.isViewFxFeeDetail];
        minFxFee = product.minFxFee || minFxFee;
        maxFxFee = product.maxFxFee || maxFxFee;
        minFxFeeRate = product.minFxFeeRate || minFxFeeRate;
        maxFxFeeRate = product.maxFxFeeRate || maxFxFeeRate;
        isViewFxFeeDetail = product.isViewFxFeeDetail || isViewFxFeeDetail;
        console.log("利润值：" + minFxFee + " " + maxFxFee + " " + minFxFeeRate + " " + maxFxFeeRate + " " + isViewFxFeeDetail + " ")

        //获取价格区间
        if (skus.length > 0) {
          for (let s = 0; s < skus.length; s++) {
            skuPrices.push(skus[s].price);
          }
          if (skuPrices.length > 0) {
            minPrice = Math.min(...skuPrices);
            maxPrice = Math.max(...skuPrices);
          }
        } else {
          minPrice = product.price;
          maxPrice = product.price;
        }
        //商品主图轮播
        for (let i = 0; i < product.itemimags.length; i++) {
          proImgs.push(product.itemimags[i].imgs);
        }
        //字符串替换
        itemDesc = itemDesc.replace('<h2d-title">', '<h2d-title>');
        itemDesc = itemDesc.replace('<div">', '<div>');
        itemDesc = itemDesc.replace('<p">', '<p>');
        itemDesc = itemDesc.replace('</p">', '</p>');
        itemDesc = itemDesc.replace('</div">', '</div>');
        itemDesc = itemDesc.replace('</h2d-title">', '</h2d-title>');

        //更新本地数据
        that.setData({
          showLoadding: false,
          minPrice: minPrice, 
          maxPrice: maxPrice,
          product: product,
          showPage: true,
          placeData: placeData,//商品地理位置信息
          itemDesc: itemDesc,//商品详情
          proImgs: proImgs, //商品主图轮播
          minFxFee: minFxFee,
          maxFxFee: maxFxFee,
          minFxFeeRate: minFxFeeRate,
          maxFxFeeRate: maxFxFeeRate,
          isViewFxFeeDetail: isViewFxFeeDetail,
          shopInfo: shopInfo,//店铺信息，用于控制展示分销利润
        })
        //html转化view商品详情
        WxParse.wxParse('itemDesc', 'html', itemDesc, that, 5);

            // that.progressAnimation();

        //下载海报文件资源到本地
        console.log('海报posterUrl:' + posterUrl)
        wx.downloadFile({
          url: posterUrl,//商品图片地址
          success: function (sres) {
            console.log(sres);
            //设置商品信息
            that.setData({
              posterUrl: sres.tempFilePath //海报资源路径
            })
            console.log("保存海报文件资源临时路径：" + that.data.posterUrl);
          }
        })
      } else {//该店铺内查询不到此商品信息
        wx.showModal({
          title: '提示',
          content: '该商品在店铺内已下架，去看看别的吧~',
          showCancel: false,
          confirmText: '知道了',
          success: function (res) {
            console.log('没有商品跳转到home欢迎页');
            app.backToHome(this);
          }
        })
      }
  
    });
       
     
  },
  getMapRoute:function(){
    let placeData = JSON.stringify(this.data.placeData) ;
    console.log(placeData);
    wx.navigateTo({
      url: '/pages/product/pages/map-route/map-route?placeData=' + placeData
    })
  },
  //预览canvas
  previewCanvas:function(){
    let that = this;
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      canvasId: 'myCanvas',
      fileType: 'png',
      success: function (res) {
        console.log(res)
        //reImgUrl: res.tempFilePath
        console.log("生成分享图片临时地址" + res.tempFilePath);
        //生成图片保存本地
        that.setData({
          previewUrl: res.tempFilePath
        })
        wx.previewImage({
          current: res.tempFilePath,
          urls: [res.tempFilePath]
        })
      }
    })
  },
  scrollFun: function (e) {

    let [that, scrollTop, showTopBtn] = [this, e.detail.scrollTop, this.data.showTopBtn]
    if (scrollTop > 600 && !showTopBtn) {
      console.log(e);
      var animation = wx.createAnimation({
        duration: 500,
        timingFunction: 'ease',
      })
      this.animation = animation
      animation.translateX(-50).opacity(0.8).step();
      that.setData({
        scorllTopAnimationData: animation.export(),
        showTopBtn:true
      })
    } 
    if (scrollTop <= 600 ){
      var animation = wx.createAnimation({
        duration: 500,
        timingFunction: 'ease',
      })
      this.animation = animation
      animation.translateX(0).opacity(0).step();
      //回到顶部按钮
      this.setData({
        scorllTopAnimationData: animation.export(),
        showTopBtn: false
      })
    }
  },
  returnTop: function () {//回到顶部事件
    this.setData({
      scroll_top: 0,
      showTopBtn: false
    })
  },
  selloutTip:function(){//售空提示
    util.showToast('该商品已售罄,再看看别的商品吧', 1000, 'none', function () { });
  },
  //用户登录
  getUserInfo: function (e) {
    console.log('用户登录');

    //查看是否允许授权
    let [that, errMsg] = [this, e.detail.errMsg];

    if (errMsg == 'getUserInfo:ok') {

      that.userLogin(e);

    } else {//未授权，打开设置

      //设置登录按钮状态
      that.setData({
        isLogin: false,//此时用户可点击登录按钮
      })
      app.connectionTimeout('请允许获得您的公开信息（头像、昵称）用于登录');
     
    }
  },

   //用户登录点击登录按钮
  userLogin: function (e) {
    console.log('用户登录');

    //查看是否允许授权
    let [that, shareKey] = [this, this.data.shareKey];
    let isAuthorization = '';

    that.setData({
      isLogin: true,//是否点击登录按钮
    })
      //登录动画
    app.userLogin(e,that);//携带onload分享的shopuid 数据

    //周期执行函数改变函数登录态
    var loginInterval = setInterval(function () {

      isAuthorization = app.data.isAuthorization;

      if (isAuthorization === true) {//已登录成功
        clearInterval(loginInterval);//停止周期循环任务
        that.cancelAnimation();//登录后关闭登录动画
        //获取店铺信息
        let shopInfo = wx.getStorageSync('shopInfo') || {};
        if (shareKey == '0' && shopInfo.isOwnShop != '1') {//没有自己的店铺

          //设置店铺信息 根据店铺信息查找订单、购物车数量
          that.setShopInfo();

        } else {
          //根据店铺id 查商品
          that.QueryitemByItemId();
          //获取订单、购物车数量
          that.getElementsCounts();
        }

        that.setData({
          isAuthorization: app.data.isAuthorization,
          isBindPhone: wx.getStorageSync('isBindPhone'), //根据绑定状态获取用户授权
        })
      }
    }, 100)

    //十秒钟提示网络链接超时重试
    setTimeout(function () {

      //网络链接超时的可能
      if (isAuthorization !== true) {
        clearInterval(loginInterval);//停止周期循环任务
        console.log('客户端登录情况isAuthorization：' + isAuthorization);
        //超时重新登录提示
        that.connectionTimeout("网络链接异常,请重新登录");
        that.setData({
          isLogin: false,//是否点击了登录按钮
        })
      } else {
        console.log('定时任务结束');
      }
    }, 1000 * 10);
   
  },
  //设置shopuid、 inviter根据店铺信息查找订单、购物车数量(前提：自己没有店铺)
  setShopInfo:function(){
    console.log('setShopInfo');

    let [that, shopuid, inviter, shopInfo] = [this, this.data.shopuid, this.data.inviter, wx.getStorageSync('shopInfo')||{}];
 
    //如果是用户绑定的不是自己的店铺，而且没有分享店铺id,查询分享人有没有店铺
    http.getReq('/weixin/getShopInviter', {
      shopuid: shopuid,
      inviter: inviter
    } ,function (res) {

      //店铺信息保存在本地---------------------------------------------
      if (res.data.shopuid && shopInfo.isOwnShop !== '1') {
        //设置参数
        //更新本地店铺数据
        shopInfo.shopuid = res.data.shopuid; //店铺id
        shopInfo.shopName = res.data.shopName;//店铺名称
        shopInfo.isOwnShop = '';//是否为自己的店铺
      }

      //更新店铺信息,若是平台分享则保留原有 shopInfo
      wx.setStorageSync('shopInfo', shopInfo);
      console.log('显示的店铺信息应为：');
      console.log(wx.getStorageSync('shopInfo'));

      //根据店铺id 查商品
      that.QueryitemByItemId();
      //获取订单、购物车数量
      that.getElementsCounts();
    });

  },
  //替换轮播图加载不出时图片
  errSwiperImg:function(e){
    let proImgs = this.data.proImgs;//轮播商品图片
    let imgIndex = e.currentTarget.dataset.imgindex;//商品下标
    proImgs[imgIndex] = app.data.defaultImgUrl;
    this.setData({
      proImgs: proImgs
    })
  },

  getFormId: function (e) {
    console.log(e);
    app.getFormId(e);
  },
  //获取进度条加载进度
  getProgress:function(){
    //页面加载进度条
    let that = this;
    progress = setInterval(function () {
      let showPage = that.data.showPage
      let progressPercent = that.data.progressPercent;
      let progressOp = that.data.progressOp;//进度条透明度
      if (showPage){
        progressPercent = 100;
      }else{
        if (progressPercent < 90){//进度条
          progressPercent++;
        }
      }

      if (progressOp > 0.5) {//进度条透明度
        progressOp = progressOp - 0.05;
      }

      //并且把当前的进度值设置到progress中
      that.setData({
        progressPercent: progressPercent,//比例
        progressOp: progressOp //透明度
      })

      //当进度条为100时清除定时任务
      if (progressPercent >= 100 ) {
        
        // that.progressAnimation();        
        clearInterval(progress);
        var changeProgressHeight = setInterval(function(){//改变进度条高度任务
          let progressHeight = that.data.progressHeight;
          if (progressHeight == 0){
            clearInterval(changeProgressHeight);//清除

          }else{
            progressHeight -= 1;
          }
          that.setData({
            progressHeight: progressHeight
          })
        },10)
      }
    },5);

  },
  //隐藏进度条动画
  progressAnimation:function(){
    let that = this;
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease',
    })

    this.animation = animation

    animation.opacity(0).height(0).step()

    this.setData({
      progressAnimation: animation.export()
    })
    // setTimeout(function(){
    //   that.setData({
    //     progressHeight: 0
    //   })
    // },1000)
  },
  //打开设置，保存海报
  bindopensetting:function(e){
    console.log(e);

    let that = this;
    let errMsg = e.detail.errMsg;
    let authSetting = e.detail.authSetting['scope.writePhotosAlbum'];
    if (authSetting == true){//同意授权
      let localPosterUrl = that.data.localPosterUrl; //本地海报路径
      
      wx.saveImageToPhotosAlbum({
        filePath: localPosterUrl,
        success: function (save_res) {
          console.log(save_res);
          app.connectionTimeout('保存成功');
        },
        fail:function(){
          app.connectionTimeout('保存失败');
        },
        complete:function(){
          that.cancelSettingBox();
        }
      })
    }

  },
  cancelSettingBox: function () { //关闭设置提示窗
    app.cancelSettingBox();
    this.setData({
      showSettingBox: app.data.showSettingBox
    })
  },
  showSettingBox: function () {//打开设置提示窗
    app.showSettingBox();
    this.setData({
      showSettingBox: app.data.showSettingBox,
      authorizeMsg: '保存图片到相册',//授权信息提示
    })
  },
  // 跳转至视频详情页
  toDetailVideo:function(e){
    console.log('跳转至视频详情页');
    console.log(e);
    let videoSrc = e.currentTarget.dataset.videosrc;
    wx.navigateTo({
      url: '/pages/product/pages/detailVideo/detailVideo?videoSrc=' + videoSrc,
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })

  },
  //播放视频
  playVideo:function(e){
    this.setData({
      showVideo:true
    })
  }
})

